// 时间戳转化成YMD格式
const dateFormat = (timestamp, formats, isZero = true) => {
  // formats格式包括
  // 1. Y-m-d
  // 2. Y-m-d H:i:s
  // 3. Y年m月d日
  // 4. Y年m月d日 H时i分
  formats = formats || 'Y-m-d';
  const zero = function(value) {
    if (value < 10 && isZero) {
      return '0' + value;
    }
    return value;
  };
  const myDate = timestamp ? new Date(timestamp) : new Date();
  const year = myDate.getFullYear();
  const month = zero(myDate.getMonth() + 1);
  const day = zero(myDate.getDate());
  const hour = zero(myDate.getHours());
  const minite = zero(myDate.getMinutes());
  const second = zero(myDate.getSeconds());

  return formats.replace(/Y|m|d|H|i|s/ig, function(matches) {
    return ({
      Y: year,
      m: month,
      d: day,
      H: hour,
      i: minite,
      s: second
    })[matches];
  });
};

// 移除 element-ui 插入进body元素下的所有popper
const removePopper = () => {
  const popper = document.getElementsByClassName('el-popper');
  popper && Array.from(popper).forEach(element => {
    element.innerHTML = '';
  });
};

// 将 1，2，3，4 转化为 周一 周二 周三 周四
const weekSwitch = function(val) {
  if (val) {
    const num = Number(val);
    switch (num) {
      case 1:
        return '周一';
      case 2:
        return '周二';
      case 3:
        return '周三';
      case 4:
        return '周四';
      case 5:
        return '周五';
      case 6:
        return '周六';
      case 7:
        return '周日';
    }
  }
};

// 暂停函数
const timeout = function(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
};

// 节流函数
const throttleFunc = () => {
  let timer = null;
  return function(fn, delay) {
    if (timer) return;
    fn();
    timer = setTimeout(() => {
      timer = null;
    }, delay);
  };
};

// 第一次立即执行防抖函数
const debounceGenerater = () => {
  let timer = null;
  let count = 0;
  return function(fn, delay) {
    timer && clearTimeout(timer);
    if (count === 0) { // 第一次立即执行
      fn();
      count++;
    } else {
      timer = setTimeout(() => {
        fn();
        count = 0;
      }, delay);
    }
  };
};

// 生成唯一字符串
const createUniqueString = () => {
  const timestamp = +new Date() + '';
  const randomNum = parseInt((1 + Math.random()) * 65536) + '';
  return (+(randomNum + timestamp)).toString(32);
};

// 获取元素样式
const getStyle = (dom, name) => {
  // 正常的浏览器方式
  // return getComputedStyle(dom,null)[name];
  // ie8的方式
  // return dom.currenStyle[name];
  if (window.getComputedStyle) {
    return getComputedStyle(dom, null)[name];
  } else {
    return dom.currenStyle[name];
  }
};

export default {
  dateFormat, removePopper, weekSwitch, timeout,
  throttleFunc, debounceGenerater, createUniqueString, getStyle
};
